<?php

namespace backend\widgets\Chart;

use yii\base\Widget;
use yii\data\SqlDataProvider;
use yii\helpers\Json;

class SalesPushkinCancellWidget extends Widget
{
    public $event_id;
    private $sales;

    public function init()
    {
        $this->sales = \Yii::$app->db->createCommand('
            SELECT SUM(`tariff`) as summ, COUNT(*) as count, `is_cancell`
            FROM `ticket_sales`
            WHERE `event_id`=:event_id AND `payment_method`=:payment_method
            GROUP BY `is_cancell`
        ', [':event_id' => $this->event_id, ':payment_method' => 'Оплата Пушкинской картой'])->queryAll();

        parent::init();
    }

    public function run()
    {   
        $this->registerPlugin();
        echo '<div>
              <canvas id="SalesPushkinCancellChart"></canvas>
          </div>';
    }

    protected function registerPlugin()
    {

        $view = $this->getView();

        ChartAsset::register($view);
        
        $jsonSales = Json::encode($this->sales);

        $view->registerJs("
            const salesPushkinCancellCanvas = document.getElementById('SalesPushkinCancellChart');
            const dataPushkinCancellSales = " . $jsonSales . ";
            const pushkinCancellColor = []; 

            for(i = 0; i < dataPushkinCancellSales.length; i++)
            {
                if(dataPushkinCancellSales[i].is_cancell == 0) 
                {
                    dataPushkinCancellSales[i].is_cancell = 'не погашены'
                    pushkinCancellColor.push('#d9534f');
                }
                if(dataPushkinCancellSales[i].is_cancell == 1) 
                {
                    dataPushkinCancellSales[i].is_cancell = 'погашены'
                    pushkinCancellColor.push('#4cae4c');
                }
            }
            
            new Chart(salesPushkinCancellCanvas, {
                type: 'pie',
                data: {
                    labels: dataPushkinCancellSales.map(row => row.is_cancell),
                    datasets: [{
                        label: 'Количество билетов',
                        data: dataPushkinCancellSales.map(row => row.count),
                        borderWidth: 1, 
                        backgroundColor: pushkinCancellColor,
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                    legend: {
                        position: 'top',
                    },
                    title: {
                        display: true,
                        text: 'Гашение Пушкинской карты'
                    }
                    }
                },
            });");
        }


}
